<template>
    <div>
        <div>
            <Breadcrumb name1="后台管理" name2="角色管理"></Breadcrumb>
            <el-card>
                <div class="search">
                    <div class="search-up">
                        <span>搜索</span>
                        <el-button @click="addDialog=true" style="border: 1px solid #0846B9;color:#0846B9">+新增</el-button>
                    </div>
                    <div class="i"><i class="el-icon-caret-top"></i></div>
                    <div class="search-down">
                        <span>角色名称:</span>
                        <el-input class="search-input" v-model="searchKeyword" clearable size="mini"></el-input>
                        <div class="search-down-btn">
                            <el-button size="small" @click="search" style="color:white;background-color: #0846B9">搜索</el-button>
                            <el-button size="small" @click="resetsearch" style="border: 1px solid #0846B9;color:#0846B9">重置</el-button>
                        </div>
                    </div>
                </div>
                <div class="wrapper">
                    <!-- 表格 -->
                    <el-table :data="roleList.slice((pageIndex-1)*pageSize,pageIndex*pageSize)" border
                    :span-method="objectSpanMethod"
                    style="width: 100%" v-loading="loading">
                        <el-table-column
                        prop="role_name" label="角色名称" width="180" align="center">
                            <template slot-scope="scope">
                                <el-button type="text"
                                @click="updateDialogBtn(scope.row.role_id,scope.row.role_name)">
                                    {{scope.row.role_name}}
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="governmenttype_name" label="监管部门" width="180" align="center"></el-table-column>
                        <el-table-column prop="menu_name" label="权限设置" align="center"></el-table-column>
                        <el-table-column label="操作" width="100" align="center">
                            <template slot-scope="scope">
                                <!-- 权限设置的对话框 -->
                                <el-button type="text" class="el-btn"
                                    @click="menuDialogBtn(scope.row)">
                                    权限设置
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 分页 -->
                    <div class="page">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="roleInfo.pageIndex"
                            :page-sizes="[5, 10, 15, 20]"
                            :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="totalRecords">
                        </el-pagination>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 新增的对话框 -->
        <el-dialog
            title="角色信息新增"
            :visible.sync="addDialog"
            width="50%"
            append-to-body>
            <el-form :model="addRoleForm" :rules="RoleFormRules"
                ref="addRoleFormRef" label-width="150px">
                <el-form-item label="角色名称：" prop="role_name">
                    <el-input v-model="addRoleForm.role_name"></el-input>
                </el-form-item>
                <el-form-item label="监管部门类型：" prop="governmenttype_ids">
                    <el-select v-model="addRoleForm.governmenttype_ids" multiple placeholder="请选择">
                        <el-option v-for="(item,index) in govlist" :key="index"
                        :label="item.governmenttype_name" :value="item.governmenttype_id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addRole">提交</el-button>
                <el-button @click="addDialog = false">取消</el-button>
            </span>
        </el-dialog>

        <!-- 编辑的对话框 -->
        <el-dialog
            title="角色信息编辑"
            :visible.sync="updateDialog"
            width="50%"
            append-to-body>
            <el-form :model="updateRoleForm" :rules="RoleFormRules"
                ref="updateRoleFormRef" label-width="150px">
                <el-form-item label="角色名称：" prop="role_name">
                    <el-input v-model="updateRoleForm.role_name"></el-input>
                </el-form-item>
                <el-form-item label="监管部门类型：" prop="governmenttype_ids">
                    <el-select v-model="updateRoleForm.governmenttype_ids" multiple placeholder="请选择">
                        <el-option v-for="(item,index) in govlist" :key="index"
                        :label="item.governmenttype_name" :value="item.governmenttype_id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="updateRole">提交</el-button>
                <el-button @click="updateDialog = false">取消</el-button>
            </span>
        </el-dialog>

        <!-- 权限设置的对话框 -->
        <el-dialog
            title="权限设置"
            :visible.sync="menuDialog"
            width="80%"
            append-to-body>
            <div class="menubtn">
                <el-button @click="allChecked" icon="el-icon-folder-checked" size="small" style="border: 1px solid #0846B9;color:#0846B9">全选</el-button>
                <el-button @click="notChecked" icon="el-icon-folder-delete" size="small" style="border: 1px solid #0846B9;color:#0846B9">全不选</el-button>
                <el-button @click="addMenu" icon="el-icon-collection" size="small" style="border: 1px solid #0846B9;color:#0846B9">保存</el-button>
            </div>
                <!-- 表格 -->
                <el-checkbox-group v-model="checkedlist">
                    <el-table :data="menuList" border >
                        <el-table-column type="index" label="序号" width="100" align="center"></el-table-column>
                        <el-table-column label="一级菜单" align="center">
                            <template v-slot="scope">
                                <el-checkbox
                                @change="changeP($event,scope.row.menu_id)"
                                :label="scope.row.menu_id">
                                {{scope.row.menu_name}}
                                </el-checkbox>
                            </template>
                        </el-table-column>
                        <el-table-column label="二级菜单" align="center">
                            <template v-slot="scope">
                                <el-row v-for="(item, index) in scope.row.children" :key="index">
                                    <el-checkbox
                                    @change="changeC($event,item.menu_pid)"
                                    :label="item.menu_id">{{ item.menu_name }}
                                    </el-checkbox>
                                </el-row>
                            </template>
                        </el-table-column>
                        <el-table-column prop="menu_remark" label="备注" align="center"></el-table-column>
                    </el-table>
                </el-checkbox-group>
        </el-dialog>

    </div>
</template>

<script>
import { request } from '../../../../api/axios'
import Breadcrumb from "../components/Breadcrumb.vue"

export default {
    name:"Role",
    components:{Breadcrumb},
    data(){
        return{
            // 获取角色列表的参数
            roleInfo:{
                ilist: [
                    {
                    title: "string",
                    content: "string"
                    }
                ]
            },
            // 分页
            pageIndex: 1,   //第几页
            pageSize: 10,   //一页几条
            // 获取到的角色列表数据
            roleList:[],
            totalRecords:0,
            locallist:"",   //搜索事件时数据暂存至locallist中
            loading:true,

            // 搜索框输入的关键词
            searchKeyword:"",
            // 搜索结果
            searchResult:[],
            searchResultRecords:0,

            // 新增对话框的显示与隐藏
            addDialog:false,
            // 新增角色的参数
            addRoleForm:{
                role_name: "",
                governmenttype_ids: [],
                // organization_id: "",
                // role_remark: ""
            },
                // 请求来的监管类型列表
                govlist:[],

            // 编辑对话框的显示与隐藏
            updateDialog:false,
            // 编辑角色的参数
            updateRoleForm:{
                role_id:"",
                role_name: "",
                governmenttype_ids: [],
                // organization_id: "",
                // role_remark: ""
            },

            // 权限设置对话框的显示与隐藏
            menuDialog:false,
            // 获取到的所有权限菜单，用来渲染权限设置表格
            menuList:[],
            // 权限设置发送请求参数
            addMenuInfo:{
                governmenttype_id: "",
                role_id: "",
                menu_ids: []
            },
            // 是否选中
            checked:false,
            // 获取到的已选中的权限，用于在打开权限设置对话框时渲染已勾选的项
            checkedlist:[],

            // 合并单元格的参数
            rowList:[],
            spanArr:[],     //返回的是相对应的行合并行数
            position:0,

            // 表单验证规则
            RoleFormRules:{
                role_name:[
                    {required:true,message:"请输入角色名称",trigger:"blur"},
                    {min:1,max:50,message:"长度在 1 到 50 个字符",trigger:"blur"}
                ],
                governmenttype_ids:[{required:true,message:"请选择监管部门类型",trigger:"blur"},]
            },
        }
    },
    created(){
        this.getRoleList();
        this.getGovList()
            this.getMenu()
    },
    methods:{
        // 获取角色列表
        getRoleList(){
            request("post","/Role_Info/GetAllStatus",this.roleInfo)
            .then(res =>{
                console.log(res)
                this.roleList=res.resultList
                this.totalRecords=res.totalRecords
                this.locallist=res.resultList
                this.rowspan()  //获取到页面后运行合并单元格函数
                this.loading=false
            })
        },

        // 搜索事件
        search(){
            this.roleList=this.locallist
            this.searchResult=[]
            console.log(this.searchKeyword)
            for(let i=0;i<this.roleList.length;i++){
                if(this.roleList[i].role_name.indexOf(this.searchKeyword) >-1){
                    this.searchResult.push(this.roleList[i])
                    this.searchResultRecords+=1
                }
            }
            this.roleList=this.searchResult
            this.totalRecords=this.searchResultRecords
        },
        // 重置搜索框
        resetsearch(){
            this.searchKeyword=""
            this.getRoleList()
        },

        // 合并单元格函数
        rowspan() {
            this.rowList=[],
            this.spanArr=[],
            this.position=0
            // 获取到这一页的数据，再进行合并单元格
            let List = this.roleList.slice((this.pageIndex-1)*this.pageSize,this.pageIndex*this.pageSize)
            List.forEach((item,index) => {
                if( index === 0){
                    this.spanArr.push(1);
                    this.position = 0;
                }
                else{
                    if(List[index].role_name === List[index-1].role_name ){
                        this.spanArr[this.position] += 1;
                        this.spanArr.push(0);
                    }else{
                        this.spanArr.push(1);
                        this.position = index;
                    }
                }
            })
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {  //row:行，column:列，rowIndex columnIndex:行和列的序号
            if (columnIndex === 0) {
                const _row = this.spanArr[rowIndex];
                const _col = _row>0 ? 1 : 0;
                return {
                    rowspan: _row,
                    colspan: _col
                }
            }
        },

        // 新增角色信息
        addRole(){
            this.$refs.addRoleFormRef.validate(valid =>{
                if(!valid) return
                request("post","/Role_Info/InsertStatus",this.addRoleForm)
                .then(res =>{
                    console.log(res)
                    this.addDialog=false
                    this.getRoleList()
                    // 提示
                    if(res.result==1){
                        this.$message({
                            type: 'success',
                            message: res.resultDesc,
                        });
                    }
                    else{
                        this.$message({
                            type: 'warning',
                            message: res.resultDesc,
                        });
                    }
                })
            })
        },
            // 请求来监管类型
            getGovList(){
                request("post","/Role_Info/GetitemStatus",this.roleInfo)
                .then(res =>{
                    console.log(res)
                    this.govlist=res.resultList
                })
            },

        // 编辑角色对话框
        updateDialogBtn(role_id,role_name){
            this.updateRoleForm.governmenttype_ids=[]
            this.updateDialog=true
            this.updateRoleForm.role_id=role_id
            this.updateRoleForm.role_name=role_name
            for(let i=0;i<this.roleList.length;i++){
                if(this.roleList[i].role_id==role_id){
                    this.updateRoleForm.governmenttype_ids.push(this.roleList[i].governmenttype_id)
                }
            }
        },
        // 编辑角色信息
        updateRole(){
            this.$refs.updateRoleFormRef.validate(valid =>{
                if(!valid) return
                request("post","/Role_Info/UpdateStatus",this.updateRoleForm)
                .then(res =>{
                    console.log(res)
                    this.updateDialog=false,
                    this.getRoleList()
                    // 提示
                    if(res.result==1){
                        this.$message({
                            type: 'success',
                            message: res.resultDesc,
                        });
                    }
                    else{
                        this.$message({
                            type: 'warning',
                            message: res.resultDesc,
                        });
                    }
                })
            })
        },

        // 权限设置对话框
        menuDialogBtn(list){
            console.log(list)
            this.menuDialog=true
            this.checkedlist=[]
            this.addMenuInfo.menu_ids=[]
            // this.getMenu()
            this.addMenuInfo.governmenttype_id=list.governmenttype_id
            this.addMenuInfo.role_id=list.role_id
            let info={
                pageIndex: 0,
                pageSize: 0,
                ilist: [
                    {
                    title: "role_id",
                    content:list.role_id,
                    },
                    // {
                    // title: "governmenttype_id",
                    // content:list.governmenttype_id,
                    // },
                ]
            }
            request("post","/Role_Info/GetMenuStatus",info)
            .then(res =>{
                console.log(res)
                for(let i=0;i<res.resultList.length;i++){
                    if(res.resultList[i].governmenttype_id==list.governmenttype_id){
                        // console.log(res.resultList[i])
                        this.checkedlist.push(res.resultList[i].menu_id)
                    }
                }
                // this.checkedlist=res.resultList
                console.log(list.governmenttype_id)
                console.log(this.checkedlist)
            })
        },
            // 获取权限菜单
            getMenu(){
                request("post","/Role_Info/GetMenuAllStatus",this.roleInfo)
                .then(res =>{
                    console.log(res)
                    this.menuList=res.resultList
                })
            },
        // 点击一级菜单选项框,二级子选项框全部选中
        changeP(event,menu_id){
            console.log(event)
            console.log(menu_id)
            if(event){
                this.menuList.forEach((item1,index) => {
                    if(item1.children!=null && item1.menu_id==menu_id){
                        item1.children.forEach((item2,index2)=>{
                            this.checkedlist.push(item2.menu_id)
                        })
                    }
                })
                // for(let i=0;i<this.menuList.length;i++){
                //     if(this.menuList[i].menu_id==menu_id && this.menuList[i].children!=null){
                //         for(let j=0;j<this.menuList[i].children.length;j++){
                //             this.checkedlist.push(this.menuList[i].children[j].menu_id)
                //         }
                //     }
                // }
                console.log(this.checkedlist)
            }
            else{
                this.menuList.forEach((item1,index1) => {
                    if(item1.children!=null && item1.menu_id==menu_id){
                        item1.children.forEach((item2,index2)=>{
                            this.checkedlist.forEach((item3,index3)=>{
                                if(item2.menu_id==item3){
                                    this.checkedlist.splice(index3,1)
                                }
                            })
                        })
                    }
                })
                // for(let i=0;i<this.menuList.length;i++){
                //     if(this.menuList[i].menu_id==menu_id && this.menuList[i].children!=null){
                //         for(let j=0;j<this.menuList[i].children.length;j++){
                //             for(let z=0;z<this.checkedlist.length;z++){
                //                 if(this.checkedlist[z]==this.menuList[i].children[j].menu_id){
                //                     this.checkedlist.splice(z,1)
                //                 }
                //             }
                //         }
                //     }
                // }
                console.log(this.checkedlist)
            }
        },
        changeC(event,menu_pid){
            console.log(event)
            console.log(menu_pid)
            if(event){
                if(this.checkedlist.indexOf(menu_pid)==-1){
                    this.checkedlist.push(menu_pid)
                }
                console.log(this.checkedlist)
            }
            else{
                let n=0
                this.menuList.forEach((item1,index)=>{
                    if(item1.menu_id==menu_pid){
                        item1.children.forEach((item2,index2)=>{
                            if(this.checkedlist.indexOf(item2.menu_id)>-1){
                                n+=1
                            }
                            if(n==0){
                                this.checkedlist.forEach((item3,index3)=>{
                                    if(item3==menu_pid){
                                        this.checkedlist.splice(index3,1)
                                    }
                                })
                            }
                        })
                    }
                })
                console.log(this.checkedlist)
                // let n=0
                // for(let i=0;i<this.menuList.length;i++){
                //     if(this.menuList[i].menu_id==menu_id){
                //         for(let j=0;j<this.menuList[i].children.length;j++){
                //             if(this.checkedlist.indexOf(this.menuList[i].children[j].menu_id)>-1){
                //                 n+=1
                //             }
                //             if(n==0){
                //                 for(let z=0;z<this.checkedlist.length;z++){
                //                     if(this.checkedlist[z]==menu_id){
                //                         this.checkedlist.splice(z,1)
                //                     }
                //                 }
                //             }
                //         }
                //     }
                // }
            }
        },
        // 点击保存
        addMenu(){
            console.log("发送请求前")
            console.log(this.checkedlist)
            this.addMenuInfo.menu_ids=this.checkedlist
            if(this.addMenuInfo.menu_ids.length==0){
                this.$message({
                    message: '请选择要设置的权限',
                    type: 'warning'
                });
            }
            else{
                request("post","/Role_Info/InsertMenuStatus",this.addMenuInfo)
                    .then(res =>{
                        console.log(res)
                        this.getRoleList()
                        // 提示
                        if(res.result==1){
                            this.$message({
                                type: 'success',
                                message: res.resultDesc,
                            });
                        }
                        else{
                            this.$message({
                                type: 'warning',
                                message: res.resultDesc,
                            });
                        }
                    }).catch(err=>{
                        console.log(err)
                    })
                this.menuDialog=false
            }
            
        },
        // 点击全选
        allChecked(){
            console.log("全选")
            this.checkedlist=[]
            this.checkedlist.push(this.menuList[0].menu_id)
        },
        // 点击全不选
        notChecked(){
            console.log("全不选")
            this.checkedlist=[]
            console.log(this.checkedlist)
        },

        // 分页的设置
        // 一页几条
        handleSizeChange(newSize){
            console.log(newSize)
            this.pageSize=newSize
            this.rowspan()
        },
        // 点击设置第几页
        handleCurrentChange(newPage){
            console.log(newPage)
            this.pageIndex=newPage
            this.rowspan()
        }
    }
}
</script>

<style scoped>
.el-card{
    height: 100%;
    margin-top: 20px;
    background-color: #F5F7FB;
}
.wrapper{
    padding: 40px 30px 20px;
    background-color: white;
}

/* 对话框 */
.el-form{
    padding-right:30px;
}
.el-form .el-form-item .el-input,.el-select{
    width: 100%;
}

/* 分页 */
.page{
    background-color: white;
}
.el-pagination{
    padding-top: 20px;
}

/* 搜索布局开始 */
.search{
    width: 100%;
    margin-bottom: 40px;
}
.search .el-button{
    color: #0846B9;
}
.search .search-up{
    margin-top: 20px;
    text-align: right;
}
.search-up>span{
    margin-right: 20px;
}
.search-down{
    background-color: white;
    /* margin-top: 20px; */
    margin-top: -20px;
    padding: 30px 130px;
    text-align: left;
}
.search-input{
    width: 400px;
}
.search-down-btn{
    margin: 20px 0px 0px 400px;
    width: 130px;
}
.i{
    text-align: right;
    margin-right: 90px;
}
.el-icon-caret-top{
    font-size: 50px;
    margin-top: -10px;
    color: white;
}

/* 表格操作列的链接的下划线设置 */
.el-table .el-button{
    text-decoration: underline;
    /* color: #606266;
    padding-bottom: 1px;
    border-bottom: 1px solid;
    border-radius: 0px; */
}
.el-table .el-btn{
    text-decoration: none;
    color: #606266;
    padding-bottom: 1px;
    border-bottom: 1px solid;
    border-radius: 0px;
}

/* 全选保存按钮 */
.el-dialog .menubtn{
    text-align: right;
    margin-bottom: 20px;
}

.el-checkbox .is-checked .el-checkbox__inner{
    background-color: black;
    border: 1px solid black;
}
</style>